<?php
/**
 * Created by PhpStorm.
 * Script Name: Membertag.php
 * Create: 2023/2/18 9:56
 * Description: 用户标签
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;
use app\admin\model\BotMember;
use app\common\model\MemberTag as TagM;
use think\facade\Db;

class Membertag extends Botbase
{
    protected $needAid = false;
    protected $needBotId = true;

    /**
     * @var TagM
     */
    protected $model;
    /**
     * @var BotMember
     */
    private $memberM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new TagM();
        $this->memberM = new BotMember();
    }

    public function index(){
        if(request()->isPost()){
            $post_data = input('post.');
            $where = ['bot_id' => $this->bot['id']];
            !empty($post_data['search_key']) && $where['title'] = ['like', '%'.$post_data['search_key'].'%'];

            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList([$post_data['page'], $post_data['limit']], $where, ['id' => 'desc'], true, 1);
            } else {
                $list = [];
            }

            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '搜索词','placeholder' => '分组名称']
        ])
            ->addTopButton('addnew')
            ->addTableColumn(['title' => 'ID', 'field' => 'id'])
            ->addTableColumn(['title' => '名称', 'field' => 'title', 'minWidth' => 200])
            ->addTableColumn(['title' => '创建时间', 'field' => 'create_time', 'type' => 'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 200, 'type' => 'toolbar'])
            ->addRightButton('edit', ['class' => 'layui-btn-default','title' => '分组成员', 'href' => url('members', ['tag' => '__data_title__'])])
            ->addRightButton('edit')
            ->addRightButton('delete');
        return $builder->show();
    }

    /**
     * 添加
     */
    public function add(){
        //使用FormBuilder快速建立表单页面。
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增')  //设置页面标题
            ->setPostUrl(url('savepost')) //设置表单提交地址
            ->addFormItem('title', 'text', '名称', '30字内', [], 'required  maxlength=30');

        return $builder->show();
    }

    /**
     * 编辑
     */
    public function edit(){
        $id = input('id');
        $data = $this->model->getOneByMap(['id' => $id, 'bot_id' => $this->bot['id']]);
        if(! $data){
            $this->error('id参数错误');
        }
        //使用FormBuilder快速建立表单页面。
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑')  //设置页面标题
            ->setPostUrl(url('savepost')) //设置表单提交地址
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('title', 'text', '名称', '30字内', [], 'required  maxlength=30')
            ->setFormData($data);

        return $builder->show();
    }

    /**
     * 分组下用户
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function members(){
        if(! $tag = input('tag', '')){
            exit('参数错误');
        }

        if(request()->isPost()){
            $post_data = input('post.');
            $where = ['uin' => $this->bot['uin'], 'tags' => ['like', '%'.$tag.'%']];
            !empty($post_data['search_key']) && $where['nickname'] = ['like', '%'.$post_data['search_key'].'%'];

            $total = $this->memberM->total($where, true);
            if ($total) {
                $list = $this->memberM->getList([$post_data['page'], $post_data['limit']], $where, ['id' => 'desc'], true, 1);
            } else {
                $list = [];
            }

            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '搜索词','placeholder' => '好友或群组昵称']
        ])
            ->setDataUrl(url('members', ['tag' => $tag]))
            ->addTopButton('addnew', ['title' => '新增成员进分组', 'href' => url('addmember', ['tag' => $tag])])
            ->addTableColumn(['title' => 'wxid', 'field' => 'wxid', 'minWidth' => 150])
            ->addTableColumn(['title' => '昵称', 'field' => 'nickname', 'minWidth' => 100])
            ->addTableColumn(['title' => '分组', 'field' => 'tags', 'minWidth' => 150])
            ->addTableColumn(['title' => '操作', 'minWidth' => 100, 'type' => 'toolbar'])
            ->addRightButton('delete', ['title' => '移出分组', 'href' => url('removeMember', ['id' => '__data_id__', 'tag' => $tag])]);
        return $builder->show();
    }

    /**
     * 移出分组
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function removeMember(){
        $id = input('id', 0);
        $tag = input('tag', '');
        if(! $member = $this->memberM->getOneByMap(['id' => $id, 'uin' => $this->bot['uin']])){
            $this->error('非法操作！');
        }
        $this->memberM->updateOne(['id' => $id, 'tags' => trim(str_replace($tag, '', $member['tags']), ',')]);
        $this->success('操作成功！');
    }

    /**
     * 移入分组
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function addMember(){
        $tag = input('tag', '');
        if($this->request->isPost()){
            $post_data = input('post.');
            $this->memberM->where('wxid', 'in', explode(',', $post_data['wxids']))
                ->where('uin', $this->bot['uin'])
                ->update(['tags' => Db::raw('TRIM(LEADING "," FROM CONCAT(tags, ",'.$tag.'"))')]);
            $this->success('操作成功', '/undefined');
        }
        $data = ['tag' => $tag];
        $builder = new FormBuilder();
        $builder->setPostUrl(url('addMember', ['tag' => $tag]))
            ->addFormItem('wxids', 'chosen_multi', '选择好友', '选择好友', $this->getMembers(), 'required')
            ->setFormData($data);
        return $builder->show();
    }

}